package com.htgd.gardenexpo.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.htgd.gardenexpo.dao.GeConDeviceMapper;
import com.htgd.gardenexpo.dao.GeConMealOrderMapper;
import com.htgd.gardenexpo.dto.GoodsOrderQuery;
import com.htgd.gardenexpo.entity.GeConDevice;
import com.htgd.gardenexpo.entity.GeConIntegralGoodsOrder;
import com.htgd.gardenexpo.entity.GeConMealOrder;
import com.htgd.gardenexpo.service.DeviceService;
import com.htgd.gardenexpo.service.GeConMealOrderService;
import com.htgd.gardenexpo.utils.HttpRequest;
import com.htgd.gardenexpo.utils.TokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author: 王秀田
 * @date: 2024/11/22 10:26
 * @description: TODO
 */
@Service
public class GeConMealOrderServiceImpl extends ServiceImpl<GeConMealOrderMapper, GeConMealOrder> implements GeConMealOrderService {

    @Value("${device.item_ids}")
    private String itemIds;

    @Value("${device.tenant_id}")
    private String tenantId;

    @Value("${device.get_telescope_url}")
    private String getTelescopeUrl;

    @Value("${device.get_charge_time_url}")
    private String getChargeTimeUrl;

    @Autowired
    private GeConMealOrderMapper geConMealOrderMapper;

    @Autowired
    private DeviceService deviceService;

    @Override
    public PageInfo<GeConMealOrder> pageList(GoodsOrderQuery goodsOrderQuery, HttpServletRequest request) throws Exception {
        PageHelper.startPage(goodsOrderQuery.getPageNum(), goodsOrderQuery.getPageSize());
        String accessToken = request.getHeader("Access_token");
        String openId = TokenUtil.getUsernameFromToken(accessToken);
        LambdaQueryWrapper<GeConMealOrder> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        if(goodsOrderQuery.getValue()!=null&&goodsOrderQuery.getValue()!=""){
            lambdaQueryWrapper
                    .like(GeConMealOrder::getName,goodsOrderQuery.getValue())
                    .or()
                    .like(GeConMealOrder::getPhone,goodsOrderQuery.getValue())
                    .or()
                    .like(GeConMealOrder::getWxName,goodsOrderQuery.getValue())
                    .or()
                    .like(GeConMealOrder::getOrderNum,goodsOrderQuery.getValue());
        }
        if(goodsOrderQuery.getStartTime()!=null&&goodsOrderQuery.getStartTime()!=""
                &&goodsOrderQuery.getEndTime()!=null&&goodsOrderQuery.getEndTime()!=""){
            lambdaQueryWrapper
                    .and(w->w.between(GeConMealOrder::getCreateTime,
                            goodsOrderQuery.getStartTime(),goodsOrderQuery.getEndTime()));
        }
        if(Objects.nonNull(openId)&&openId!=""&&openId.length()!=11&&!openId.matches("[0-9]+")){
            lambdaQueryWrapper.eq(GeConMealOrder::getOpenId,openId);
            // 计算最近两个月的起始和结束日期
            LocalDate now = LocalDate.now();
            // 添加查询条件，createDate在最近两个月内
            lambdaQueryWrapper.ge(GeConMealOrder::getCreateTime, now.minus(2, ChronoUnit.MONTHS));
        }
        lambdaQueryWrapper.orderByDesc(GeConMealOrder::getCreateTime);
        List<GeConMealOrder> list = geConMealOrderMapper.selectList(lambdaQueryWrapper);
        list.stream().forEach(item->{
            if(Objects.equals(item.getType(),"1")){
                Map<String,Object> params  = new HashMap<>();
                params.put("itemId",Integer.valueOf(itemIds));
                params.put("num",Integer.valueOf(item.getNum()));
                params.put("userId",1);
                params.put("deviceType",Integer.valueOf(item.getDeviceType()));
                Map<String,Object> headers = new HashMap<>();
                headers.put("Content-Type", "application/x-www-form-urlencoded");
                headers.put("Tenant-Id",tenantId);
                try {
                    headers.put("Authorization","Bearer "+deviceService.deviceLogin());
                } catch (Exception e) {
                    e.printStackTrace();
                    item.setTime(0);
                }
                String result = null;
                try {
                    result = HttpRequest.sendHttpGetRequest(getTelescopeUrl,params,headers);
                } catch (Exception e) {
                    e.printStackTrace();
                    item.setTime(0);
                }
                if(result!=null&&result!=""){
                    JSONObject jsonObject = (JSONObject) JSONObject.parse(result);
                    Boolean ok = (Boolean) jsonObject.get("ok");
                    if(ok){
                        String time = (String) jsonObject.get("data");
                        item.setTime(Integer.valueOf(time));
                    }else{
                        item.setTime(0);
                    }
                }else{
                    item.setTime(0);
                }
            }
            if(Objects.equals(item.getType(),"2")){
                Map<String,Object> headers = new HashMap<>();
                headers.put("Content-Type", "application/x-www-form-urlencoded");
                headers.put("Tenant-Id",tenantId);
                try {
                    headers.put("Authorization","Bearer "+deviceService.deviceLogin());
                } catch (Exception e) {
                    e.printStackTrace();
                    item.setTime(0);
                }
                String result = null;
                try {
                    result = HttpRequest.sendHttpGetRequest(getChargeTimeUrl+Long.valueOf(itemIds)+"/"+Long.valueOf(item.getNum()),null,headers);
                } catch (Exception e) {
                    e.printStackTrace();
                    item.setTime(0);
                }
                if(result!=null&&result!=""){
                    JSONObject jsonObject = (JSONObject) JSONObject.parse(result);
                    Boolean ok = (Boolean) jsonObject.get("ok");
                    if(ok){
                        String time = (String) jsonObject.get("data");
                        item.setTime(Integer.valueOf(time));
                    }else{
                        item.setTime(0);
                    }
                }else{
                    item.setTime(0);
                }
            }
        });
        return new PageInfo<>(list);
    }
}
